package com.qf.controller;

import com.netflix.ribbon.proxy.annotation.Http;
import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.pojo.SmsInterfaceForm;
import com.qf.service.InterfaceService;
import com.qf.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 接口微服务
 * @author lixu
 *
 * http://127.0.0.1/sms/smsInterface
 */
@RestController
@RequestMapping("/sms")
public class InterfaceController {


    @Autowired
    private CacheFeign cacheFeign;

    @Value("${ip-header}")
    private String[] ipHeader;

    @Autowired
    private InterfaceService interfaceService;

    /**
     * 下行接口
     *  请服务方url地址：http://ip:port/sms/interface,客户方将下行数据发送到该url
     */
    @PostMapping("/smsInterface")
    public Result smInterface(SmsInterfaceForm smsInterfaceForm, HttpServletRequest request){//form-data
        //校验
        //1:clientID 是否正确  是我们数据库是否存在  2  4  6
        String key = CacheConstants.CACHE_PREFIX_CLIENT + smsInterfaceForm.getClientID();
        //Object value = cacheFeign.hget(key, "id");
        Map map = cacheFeign.hMGet(key);
        if(null == map || map.size() == 0){
            return Result.error(101,"认证错：clientId错误");
        }
        //2:**校验的方法有：**
        //
        //- 手机号合法性
        String mobile = smsInterfaceForm.getMobile();
        if(StringUtils.isEmpty(mobile)){
            return Result.error(105,"手机号错误");
        }
        String[] ms = mobile.split(",");
        if(ms.length > 100){
            return Result.error(105,"手机号错误,最多100个号码");
        }
        //正则表达式 判断手机号是否正确
        String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        Set<String> errorPhone = new HashSet<>();
        for (String m : ms) { // 100个手机号 有57个不合格  57个全提示
            if(!m.matches(regex)){
                //return Result.error(105,"手机号错误,[" + m +  "]此手机不合法");
                errorPhone.add(m);
            }
        }
        if(errorPhone.size() > 0){
            return Result.error(105,"手机号错误," + errorPhone);// []
        }
        //3、 客户密码的合法性
        String pwd = smsInterfaceForm.getPwd();
        if(StringUtils.isEmpty(pwd)) return Result.error(102,"密码错误");
        if(!pwd.equals(map.get("pwd"))){
            return Result.error(102,"密码错误");
        }
        //4、用户发送信息的长度
        String content = smsInterfaceForm.getContent();
        if(StringUtils.isEmpty(content)) return Result.error(104,"必须有短信的内容");
        if(content.length() > 500){
            return Result.error(104,"消息长度错");
        }
        //5、下行编号（srcID）错误
        String srcID = smsInterfaceForm.getSrcID();
        if(StringUtils.isEmpty(srcID)) return Result.error(106,"下行编号（srcID）错误");

        //6、客户IP的合法性
        String ip = getRealIp(request);//获取ip地址的方式是不正确的
        smsInterfaceForm.setIp(ip);
        Object ipaddress = map.get("ipaddress");
        if(!ip.equals(ipaddress)){
            return Result.error(103,"IP校验错误");
        }

        //7:将表单信息及手机相关发送到RabbitMQ  业务
        boolean isSendOK = interfaceService.sendMessage(smsInterfaceForm);

        //8:成功了
        return Result.error(0,"接收成功");

    }

    /**
     * 获取真实IP
     * @param request
     * @return
     */
    public String getRealIp(HttpServletRequest request){
        for (String ipH : ipHeader) {
            String ip = request.getHeader("ipH");
            if(!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)){
                //真实IP
                return ip;
            }
        }
        //无代理
        return request.getRemoteAddr();
    }
}
